package com.sxr.signature.impl;

import com.sxr.signature.SignRequest;
import com.sxr.signature.VerifyService;

import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.Objects;

/**
 * 基于HMAC-SHA256的签名服务实现
 * 零第三方依赖，仅使用JDK8标准库
 *
 * @author SXR
 * @since 1.0.0
 */
public class RsaVerifyService implements VerifyService {
    @Override
    public boolean verifySignature(SignRequest request, String signature) {
        Objects.requireNonNull(request);
        String secretKey = request.getSecretKey();
        Objects.requireNonNull(secretKey);
        try {
            String data = request.buildStringToSign();
            return verify(data, signature ,secretKey);
        } catch (Exception e) {
            throw new RuntimeException("rsa verify error",e);
        }
    }


    // 验签
    public static boolean verify(String data, String base64Signature, String base64PublicKey) throws Exception {
        PublicKey publicKey = base64ToPublicKey(base64PublicKey);
        Signature verifier = Signature.getInstance("SHA256withRSA");
        verifier.initVerify(publicKey);
        verifier.update(data.getBytes(StandardCharsets.UTF_8));
        byte[] signatureBytes = Base64.getDecoder().decode(base64Signature);
        return verifier.verify(signatureBytes);
    }

    // 从 Base64 字符串恢复公钥
    public static PublicKey base64ToPublicKey(String base64PublicKey) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(base64PublicKey);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePublic(keySpec);
    }
}
